import MsgCenter, {MsgType} from './MsgCenter'
import {msgHandler} from "../../store/sagas/socket";

class YfSocket {

    initWebSocket = (path, userId, msgHandler, reconnect)=> {
        if (!this.ws || reconnect) {
            this.ws = new WebSocket(path)
            this.ws.onopen = (evt) => {
                //发送连接消息
                let msgEntity = MsgCenter.createConnectMsg(userId)
                this.ws.send(MsgCenter.serializeBinary(msgEntity))
                //3秒发送一次心跳
                setInterval( ()=> {
                    let msgEntity = MsgCenter.createHeartMsg(userId)
                    this.ws.send(MsgCenter.serializeBinary(msgEntity))
                },3000)
            }
            this.ws.onclose = function (evt) {
                console.log('Ws关闭了')
            }
            this.ws.onmessage = function (evt) {
                // JSON.stringify(evt)
                let msg = MsgCenter.deserializeBinary(evt.data).toObject()
                console.log('Ws接受到了消息' + JSON.stringify(msg))
                if (msgHandler) {
                    msgHandler(msg)
                }
            }
            this.ws.onerror = function (evt) {
                console.log('连接失败了!')
            }
        }
    }


    sendMsg = (type, chatType, fromUserId, toUserId, content) => { //发送消息
        let msgEntity = MsgCenter.createMsg(type, chatType, fromUserId, toUserId, content);
        this.ws.send(MsgCenter.serializeBinary(msgEntity))
        return msgEntity.toObject()
    }


}


// function MyWebSocket() {
//
// }
//
// MyWebSocket.prototype = {
//     ws: null,
//     initWebSocket:  (path, userId ,msgHandler,reconnect)=> {
//         if (!this.ws || reconnect) {
//             this.ws = new WebSocket(path)
//             console.log(this.sendMsg)
//             this.ws.onopen =  (evt) => {
//                 //发送连接消息
//                 this.sendMsg(MsgType.CONNECT,0,userId,0,`userId:${userId}上线了`)
//             }
//             this.ws.onclose = function (evt) {
//                 console.log('Ws关闭了')
//             }
//             this.ws.onmessage = function (evt) {
//                 console.log('Ws接受到了消息' + JSON.stringify(evt.data))
//                 if (msgHandler) {
//                     msgHandler(evt.data)
//                 }
//             }
//             this.ws.onerror = function (evt) {
//                 console.log('连接失败了!')
//             }
//         }
//     },
//     sendMsg: (type, chatType, fromUserId, toUserId, content) => { //发送消息
//         console.log('====='+MyWebSocket.prototype.ws)
//         let msgEntity = MsgCenter.createMsg(type, chatType, fromUserId, toUserId, content);
//         this.ws.send(MsgCenter.serializeBinary(msgEntity))
//         return msgEntity.toObject()
//     }
// }
//
export default new YfSocket()